package site.qjdb.service.impl;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import site.qjdb.dao.CommentDao;
import site.qjdb.dao.ReplyDao;
import site.qjdb.pojo.Comment;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.Reply;
import site.qjdb.service.CommentService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
	@Resource
	private CommentDao commentDao;
	@Resource
	private ReplyDao replyDao;
	
	@Override
	public void addComment(Comment comment) {
		commentDao.addComment(comment);
	}

	/**
	 * 	这里只关联了User，没有关联Goods
	 * 
	 * */
	@Override
	public Comment findComment(Comment comment) {
		Map<String, Object> map = new HashMap<>();
		map.put("comment", comment);
		List<Comment> commentList = commentDao.selectCommentAll(map);
		if(commentList == null || commentList.size() == 0) {
			return null;
		} else {
			return commentList.get(0);
		}
	}

	@Override
	public void addLikeCount(Comment comment) {
		if(comment.getCommentId() == null) {
			return;
		}
		Integer likeCount = comment.getLikeCount();
		if(likeCount == null) {
			likeCount = new Integer("0");
		}
		likeCount++;
		// 增加点赞数
		Comment newComment = new Comment();
		newComment.setCommentId(comment.getCommentId());
		newComment.setLikeCount(likeCount);
		commentDao.updateComment(newComment);
	}

	@Override
	public List<Comment> findCommentAll(Integer gid) {
		Comment comment = new Comment();
		// 通过goods设置gid
		Goods _goods = new Goods();
		_goods.setGid(gid);
		comment.setGoods(_goods);
		// 未删除
		comment.setIsDel(0);
		Map<String, Object> map = new HashMap<>();
		map.put("comment", comment);
		// 排序规则：点赞数、时间
		map.put("orderBy", "comment.like_count desc,comment.time desc");
		List<Comment> commentList = commentDao.selectCommentAll(map);
		if(commentList == null || commentList.size() ==  0) {
			return null;
		} else {
			// 添加回复信息
			for(Comment _comment : commentList) {
				Map<String, Object> _map = new HashMap<>();
				Reply reply = new Reply();
				// 未删除
				reply.setIsDel(0);
				// 上级id
				reply.setSuperiorId(_comment.getCommentId());
				// 类型：留言
				reply.setType(0);
				_map.put("reply", reply);
				_map.put("orderBy", "reply.time desc");
				List<Reply> replyList = replyDao.selectReplyAll(_map);
				if(replyList != null && replyList.size() > 0) {
					_comment.setReplyList(replyList);
				}
			}
			return commentList;
		}
	}
}
